package com.lichuandi.crawler;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/news")
public class NewsController {

    @GetMapping("/headlines")
    public String getNewsHeadlines() {
        try {
            String url = "http://example.com/news"; // 要爬取的新闻网站URL
            Document document = Jsoup.connect(url).get();

            Elements headlines = document.select(".headline"); // 获取新闻标题的元素
            StringBuilder result = new StringBuilder();

            for (Element headline : headlines) {
                String title = headline.text(); // 获取新闻标题
                String link = headline.attr("href"); // 获取新闻链接

                result.append(title).append(": ").append(link).append("\n");
            }

            return result.toString();
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }
}
